package com.amos.generator.model.impl;

import com.amos.generator.connect.Connector;
import com.amos.generator.model.BaseGeneratorImpl;
import com.amos.generator.starter.GeneratorContext;
import com.amos.generator.starter.PackageConfigType;
import com.amos.generator.starter.PackageConfigTypes;
import com.amos.generator.util.GeneratorStringUtils;
import org.apache.velocity.VelocityContext;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 功能描述：Model代码生成
 */
@Component
public class MapGeneratorImpl extends BaseGeneratorImpl {

    @Override
    public void initVelocityContext(VelocityContext velocityContext, GeneratorContext generatorContext) {
        super.initVelocityContext(velocityContext, generatorContext);

        super.initVelocityContext(velocityContext, generatorContext);
        String tableName = generatorContext.getTableName();
        Connector connector = (Connector) generatorContext.getAttribute("connector");

        Map<String, String> keyMap = connector.getPrimaryKey(tableName);
        Map<String, String> colMap = connector.mapColumnNameType(tableName);
        Map<String, String> columnRemarkMap = connector.mapColumnRemark(tableName);
        velocityContext.put("fields", generateFields(colMap, columnRemarkMap, keyMap));
        List<String> cols = new ArrayList<>();
        List<String> pros = new ArrayList<>();
        List<String> prositem = new ArrayList<>();
        List<String> ups = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        generateColsPros(colMap, cols, pros, prositem);
        generateups(colMap, ups, ids, keyMap);
        velocityContext.put("cols", cols);
        velocityContext.put("pros", pros);
        velocityContext.put("prositem", prositem);
        velocityContext.put("ids", ids);
        velocityContext.put("ups", ups);
        velocityContext.put("column", colMap.keySet().toString());
    }

    @Override
    public PackageConfigTypes getPackageConfigTypes() {
        if (super.getPackageConfigTypes() == null || super.getPackageConfigTypes().getType() == null) {
            Set<PackageConfigType> packageConfigTypeSet = new HashSet();
            packageConfigTypeSet.add(new PackageConfigType("mapperPackage", "/mapper", "Mapper.xml", "mapper.vm"));
            PackageConfigTypes packageConfigTypes = new PackageConfigTypes();
            packageConfigTypes.setPackageConfigTypeSet(packageConfigTypeSet);
            packageConfigTypes.setType(PackageConfigTypes.ConfigType.MAPPER);
            setPackageConfigTypes(packageConfigTypes);
        }
        return super.getPackageConfigTypes();
    }

    /**
     * 组织属性
     * <resultMap id="InterestDO" type="cn.iteam.howtogo.dao.interest.InterestDO">
     * <id column="scenery_id" property="sceneryId"/>
     * <id column="user_id" property="userId"/>
     * <result column="data_status" property="dataStatus"/>
     * <result column="gmt_create" property="gmtCreate"/>
     * </resultMap>
     *
     * @author meng_lbo
     * @date 2020/8/11  14:13
     */
    protected List<String> generateFields(Map<String, String> map, Map<String, String> columnRemarkMap, Map<String, String> keyMap) {
        Set<String> keySet = map.keySet();
        List<String> fields = new ArrayList();

        for (String key : keySet) {
            StringBuilder sb = new StringBuilder();
            String value = map.get(key);
            if (keyMap.get("primaryKey").equals(key)) {
                sb.append(" <id column=\"")
                        .append(key)
                        .append("\" property=\"")
                        .append(GeneratorStringUtils.format(key))
                        .append("\"/>");

            } else {
                sb.append(" <result column=\"")
                        .append(key)
                        .append("\" property=\"")
                        .append(GeneratorStringUtils.format(key))
                        .append("\"/>");

            }
            fields.add(sb.toString());
        }
        return fields;
    }

    protected void generateColsPros(Map<String, String> map, List<String> cols, List<String> pros, List<String> prositem) {
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            cols.add(key);
            pros.add("#{" + GeneratorStringUtils.format(key) + "}");
            prositem.add("#{item." + GeneratorStringUtils.format(key) + "}");
        }
    }

    protected List<String> generateups(Map<String, String> map, List<String> ups, List<String> ids, Map<String, String> keyMap) {
        Set<String> keySet = map.keySet();
        List<String> fields = new ArrayList();
        for (String key : keySet) {
            StringBuilder sb = new StringBuilder();
            if (!keyMap.get("primaryKey").equals(key)) {
                sb.append(" <if test=\"")
                        .append(GeneratorStringUtils.format(key))
                        .append("!= null ");

                if (map.get(key).equals("String")) {
                    sb.append(" and ")
                            .append(GeneratorStringUtils.format(key))
                            .append("!= '' ");
                } else if (map.get(key).equals("Integer") || map.get(key).equals("Long") || map.get(key).equals("Double") || map.get(key).equals("BigDecimal")) {
                    sb.append(" and ")
                            .append(GeneratorStringUtils.format(key))
                            .append("!= 0 ");
                }
                sb.append("\">");
                sb.append(key).append("= #{").append(GeneratorStringUtils.format(key)).append("},");
                sb.append("</if>");
                ups.add(sb.toString());
            } else {
                sb.append("   and ").append(key).append("= #{").append(GeneratorStringUtils.format(key)).append("}");
                ids.add(sb.toString());
            }

        }
        return fields;
    }
}
